package com.z.redis.util;

import io.netty.util.internal.StringUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * @author z
 * 加载和读取文件中的关于Redis配置的属性
 */
public class PropertiesUtil {
    private PropertiesUtil() {}
    private static PropertiesUtil instance = new PropertiesUtil();//饿汉式单例
    public static PropertiesUtil getInstance() { return instance; }

    // 配置文件的加载
    public static Properties getProParams(){
        return PropertiesUtil.getInstance().getProParams("/redis_conf.properties");
    }
    public Properties getProParams(String propertiesName){
        InputStream is = getClass().getResourceAsStream(propertiesName);
        Properties prop = new Properties();
        try{
            prop.load(is);//加载配置到Properties对象
        }catch(IOException e1){
            e1.printStackTrace();
        }finally {
            if(is != null){
                try{
                    is.close();
                }catch (IOException e2){
                    e2.printStackTrace();
                }
            }
        }
        return prop;
    }
    //获得节点的IP
    public static String getNodeAddress() {
        String address = getProParams().getProperty("ip");
        if(StringUtil.isNullOrEmpty(address)){
            return "127.0.0.1";
        }
        return address;
    }
    //获得节点的端口
    public static Integer getNodePort(){
        Integer port = 6379;
        try{
            String strPort = getProParams().getProperty("port");
            port = Integer.parseInt(strPort);
        }catch (Exception e){ //格式错误或者空值
            return 6379;
        }
        if(port<=0||port>65535){ //端口范围校验
            return 6379;
        }
        return port;
    }
    // 获得aof持久化路径
    public static String getAofPath(){
        String aofDataDir = getProParams().getProperty("aof_data_dir");
        if(StringUtil.isNullOrEmpty(aofDataDir)){ return "./aof_data_dir/"; }
        return aofDataDir;
    }
    // 检查是否启用AOF
    public static boolean getAppendOnly() {
        String appendOnly = getProParams().getProperty("appendonly");
        if(!StringUtil.isNullOrEmpty(appendOnly)){
            return appendOnly.trim().equals("yes");//只有yes才开启
        }
        return false;//默认关闭
    }
    // 检查是否启用TCP keepalive
    public static boolean getTcpKeepAlive(){
        String appendOnly = getProParams().getProperty("tcp_keepalive");
        if(!StringUtil.isNullOrEmpty(appendOnly)){
            return appendOnly.trim().equals("yes");
        }
        return false;//默认关闭
    }
}
